package com.sun.filesigndemo.controller;

import com.sun.filesigndemo.common.entity.User;
import com.sun.filesigndemo.common.security.Filter.FormAuthenticationFilter;
import com.sun.filesigndemo.common.security.Realm.Principal;
import com.sun.filesigndemo.common.security.UserUtils;
import com.sun.filesigndemo.common.statusCode.GlobalResultStatusEnum;
import com.sun.filesigndemo.common.statusCode.ResultMsg;
import com.sun.filesigndemo.common.utils.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
public class AdminController extends SupportController{



    /**
     * 登录页面
     * @param request
     * @return
     */
    @RequestMapping(value="/login", method= RequestMethod.GET)
    @ResponseBody
    public Object getLogin(HttpServletRequest request){
        return ResultMsg.successMsg("请先登录！");
    }

    @RequestMapping(value="/login", method= RequestMethod.POST)
    @ResponseBody
    public Object login(HttpServletRequest request){

        Principal principal = UserUtils.getPrincipal();

        // 如果已经登录，则跳转到管理首页
        if(principal != null){
            return ResultMsg.successData(UserUtils.getUser());
        }

        String message = (String)request.getAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_PARAM);

        if (StringUtils.isBlank(message) || StringUtils.equals(message, "null")){
            message = "用户或密码错误, 请重试.";
        }

        return ResultMsg.fail(message);
    }

    @RequestMapping(value = "/logout")
    @ResponseBody
    public Map<String, Object> logout(HttpServletRequest request) {

        Session s= UserUtils.getSession();


        UserUtils.clearCache(UserUtils.getUser());
        SecurityUtils.getSubject().logout();

        return ResultMsg.success();
    }

    @RequestMapping(value="/success", method= RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> success(HttpServletRequest request) {
        User user= UserUtils.getUser();
        return ResultMsg.successData(user);
    }

//    @RequiresPermissions("user")
    @RequestMapping(value="/auth/userinfo", method= RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> userinfo(HttpServletRequest request) {
        User user= UserUtils.getUser();
        if(user.getName() != null){
            return ResultMsg.successData(user);
        }else {
            return ResultMsg.fail(GlobalResultStatusEnum.REFUSED_REQUEST);
        }

    }

}
